<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" :disabled="disabled" label-width="150px">
      <el-form-item label="活动类型：" prop="activeTypeId">
        <el-col :span="14">
          <el-select v-model="form.activeTypeId" placeholder="请选择" clearable>
            <el-option label="公益活动" :value="1" />
            <el-option label="其他" :value="2" />
          </el-select>
        </el-col>
      </el-form-item>
      <el-form-item label="封面图片：" prop="coverImg">
        <el-col :span="14">
          <UploadFile :file-list="form.coverImg" :limit="5" :disabled="disabled" @change="uploadHandle($event, 'coverImg','coverImg')">
            <div slot="tip">
              <p>最多上传5张</p>
            </div>
          </UploadFile>
        </el-col>
      </el-form-item>
      <el-form-item label="标题：" prop="title">
        <el-col :span="14">
          <el-input v-model="form.title" placeholder="请输入" clearable />
        </el-col>
      </el-form-item>
      <el-form-item label="活动时间：" prop="activityDateRange">
        <el-col :span="14">
          <el-date-picker
            v-model="form.activityDateRange"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="地址：" prop="address">
        <el-col :span="14">
          <el-input v-model="form.address" placeholder="请输入" clearable />
        </el-col>
      </el-form-item>
      <el-form-item label="是否配置报名入口：" prop="isEnroll">
        <el-col :span="14">
          <el-radio-group v-model="form.isEnroll" disabled>
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>
      <template v-if="form.isEnroll === 1">
        <el-form-item label="报名对象" prop="personnelType">
          <el-col :span="14">
            <el-checkbox-group v-model="form.personnelType">
              <el-checkbox :label="0">个人</el-checkbox>
              <el-checkbox :label="1">单位</el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-col :span="22">
            <el-radio-group v-model="form.needEnroll">
              <el-radio :label="0">需提供一位游客或联系人信息</el-radio>
              <el-radio :label="1">需要填写每个游客信息</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item>
          <el-row v-if="showPersonTypeFields">
            <el-table
              :data="form.personTypeFields"
              border
            >
              <el-table-column label="字段名称" prop="fieldName" />
              <el-table-column label="启用（显示）" prop="status">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.status" size="small" :disabled="scope.row.disabled" />
                </template>
              </el-table-column>
              <el-table-column label="必填" prop="required" width="70">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.required" size="small" :disabled="scope.row.disabled" />
                </template>
              </el-table-column>
              <el-table-column label="字段类型" prop="customType" />
              <el-table-column label="字段属性值" prop="fieldAttr" />
              <el-table-column label="提示文案" prop="fieldPrompt" width="150" />
              <el-table-column label="操作" width="100">
                <template v-if="$index>6" slot-scope="{row, $index}">
                  <el-button type="text" size="small" @click="editField(row, $index, 'person')">编辑</el-button>
                  <el-button type="text" size="small" class="danger-text-button" @click="deleteField(row, $index, 'person')">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" class="add-field" @click="addField('person')">自定义字段</el-button>
          </el-row>
          <el-row v-if="showCompanyTypeFields">
            <el-table
              :data="form.companyTypeFields"
              border
            >
              <el-table-column label="字段名称" prop="fieldName" />
              <el-table-column label="启用（显示）" prop="status">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.status" size="small" :disabled="scope.row.disabled" />
                </template>
              </el-table-column>
              <el-table-column label="必填" prop="required" width="70">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.required" size="small" :disabled="scope.row.disabled" />
                </template>
              </el-table-column>
              <el-table-column label="字段类型" prop="customType" />
              <el-table-column label="字段属性值" prop="fieldAttr" />
              <el-table-column label="提示文案" prop="fieldPrompt" width="150" />
              <el-table-column label="操作" width="100">
                <template v-if="$index>4" slot-scope="{row, $index}">
                  <el-button type="text" size="small" @click="editField(row, $index, 'company')">编辑</el-button>
                  <el-button type="text" size="small" class="danger-text-button" @click="deleteField(row, $index, 'company')">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button type="primary" class="add-field" @click="addField('company')">自定义字段</el-button>
          </el-row>
        </el-form-item>
        <el-form-item label="报名时间：" prop="activityDateRange">
          <el-col :span="14">
            <el-date-picker
              v-model="form.activityDateRange"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="是否生成使用凭证：" prop="sign">
          <el-col :span="14">
            <el-radio-group v-model="form.sign">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <template v-if="form.sign === 1">
          <el-form-item label="核销/签到时间：" prop="signInStartTime">
            <el-col :span="6" style="margin-right: 20px">
              <el-select :value="1" placeholder="请选择" clearable>
                <el-option label="活动开始前" :value="1" />
              </el-select>
            </el-col>
            <el-col :span="6">
              <el-select v-model="form.signInStartTime" placeholder="请选择" clearable>
                <el-option label="3小时" :value="0" />
                <el-option label="2小时" :value="1" />
                <el-option label="1小时" :value="2" />
                <el-option label="30分钟" :value="3" />
              </el-select>
            </el-col>
          </el-form-item>
          <el-form-item label="是否需要签退：" prop="needSignOut">
            <el-col :span="14">
              <el-radio-group v-model="form.needSignOut">
                <el-radio :label="0">不需要</el-radio>
                <el-radio :label="1">需要</el-radio>
              </el-radio-group>
            </el-col>
          </el-form-item>
        </template>
        <el-form-item label="是否免费：" prop="fee">
          <el-col :span="14">
            <el-radio-group v-model="form.fee">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <template v-if="form.fee === 0">
          <el-form-item label="活动费用：" prop="amount">
            <el-col :span="8">
              <el-input v-model="form.amount" placeholder="请输入" clearable>
                <template slot="append">元</template>
              </el-input>
            </el-col>
          </el-form-item>
          <el-form-item label="费用说明：" prop="amountDesc">
            <el-col :span="14">
              <el-input v-model="form.amountDesc" placeholder="请输入" clearable />
            </el-col>
          </el-form-item>
        </template>
        <el-form-item label="报名总数：">
          <el-col :span="14">
            <el-input v-model="form.enrollCount" placeholder="请输入" clearable />
          </el-col>
        </el-form-item>
        <el-form-item label="单次限购数：">
          <el-col :span="14">
            <el-input v-model="form.singleCount" placeholder="请输入" clearable />
          </el-col>
        </el-form-item>
      </template>
      <el-form-item label="活动内容：" prop="content">
        <el-col :span="22">
          <RichText :value.sync="form.content" :disabled="disabled" />
        </el-col>
      </el-form-item>
    </el-form>
    <div v-if="type !== 'detail'" class="form-bottom-box">
      <el-button @click="close">取消</el-button>
      <el-button type="primary" :loading="loading" @click="confirm">确定</el-button>
    </div>
    <AddField
      v-if="showAddField"
      :type="addType"
      :index="fieldIndex"
      :form-detail="fieldDetail"
      @close="closeHandle"
      @confirm="confirmHandle"
    />
  </div>
</template>

<script>
import { getActivityDetail } from '@/api/activity'
import { createActivity } from '@/api/activity'
import UploadFile from '@/components/UploadFile/index.vue'
import RichText from '@/components/RichText/index.vue'
import AddField from './AddField.vue'
import { mapGetters } from 'vuex'
export default {
  name: 'Activity',
  components: {
    UploadFile,
    RichText,
    AddField
  },
  props: {
    id: {
      type: [Number, String],
      default: ''
    },
    type: {
      type: String,
      default: 'add' // add:新增  detail:详情  edit:编辑
    }
  },
  data() {
    return {
      loading: false,
      addType: '',
      fieldIndex: -1,
      fieldDetail: {},
      showAddField: false,
      form: {
        activeTypeId: '',
        coverImg: '',
        title: '',
        activityDateRange: [],
        address: '',
        isEnroll: 0,
        // personnelType: [],
        // needEnroll: 0,
        // personTypeFields: [
        //   { fieldName: '姓名', status: true, required: true, disabled: true, customType: 1, fieldAttr: '', fieldPrompt: '请输入姓名' },
        //   { fieldName: '身份证号', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请输入身份证号' },
        //   { fieldName: '手机号', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请输入正确的手机号' },
        //   { fieldName: '地址', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请输入正确的地址' },
        //   { fieldName: '居室', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请选择居室' },
        //   { fieldName: '服务编号', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请输入服务编号' },
        //   { fieldName: '预计资助金额', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请输入预计资助金额' }
        // ],
        // companyTypeFields: [
        //   { fieldName: '单位名称', status: true, required: true, disabled: true, customType: 1, fieldAttr: '', fieldPrompt: '请输入单位名称' },
        //   { fieldName: '联系人', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请输入联系人' },
        //   { fieldName: '手机号', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请输入正确的手机号' },
        //   { fieldName: '参观时间', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请选择参观时间' },
        //   { fieldName: '预计资助金额', status: false, required: false, customType: 1, fieldAttr: '', fieldPrompt: '请输入预计资助金额' }
        // ],
        // applyDateRange: [],
        // sign: 0,
        // signInStartTime: '',
        // needSignOut: 0,
        // fee: 1,
        // amount: '',
        // amountDesc: '',
        // enrollCount: '',
        // singleCount: '',
        content: ''
      },
      rules: {
        activeTypeId: [{ required: true, message: '请选择活动类型', trigger: ['change'] }],
        coverImg: [{ required: true, message: '请上传封面图片', trigger: ['change'] }],
        title: [{ required: true, message: '请输入标题', trigger: ['blur'] }],
        activityDateRange: [{ required: true, message: '请选择活动时间', trigger: ['change'] }],
        address: [{ required: true, message: '请输入地址', trigger: ['blur'] }],
        isEnroll: [{ required: true, message: '请选择是否需要报名', trigger: ['change'] }],
        personnelType: [{ required: true, message: '请选择报名对象', trigger: ['change'] }],
        applyDateRange: [{ required: true, message: '请选择报名时间', trigger: ['change'] }],
        sign: [{ required: true, message: '请选择是否生成使用凭证', trigger: ['change'] }],
        signInStartTime: [{ required: true, message: '请选择核销/签到时间', trigger: ['change'] }],
        needSignOut: [{ required: true, message: '请选择是否需要签退', trigger: ['change'] }],
        fee: [{ required: true, message: '请选择是否免费', trigger: ['change'] }],
        amount: [{ required: true, message: '请输入活动费用', trigger: ['blur'] }],
        amountDesc: [{ required: true, message: '请输入费用说明', trigger: ['blur'] }],
        content: [{ required: true, message: '请输入活动内容', trigger: ['change'] }]
      }
    }
  },
  computed: {
    ...mapGetters([
      'currentEnterprise',
      'currentSite'
    ]),
    disabled() {
      return this.type === 'detail'
    }
    // showPersonTypeFields() {
    //   // return this.form.personnelType.includes(0)
    // },
    // showCompanyTypeFields() {
    //   // return this.form.personnelType.includes(1)
    // }
  },
  created() {
    if (this.id) {
      this.getDetail()
    }
  },
  methods: {

    // 添加字段
    addField(addType) {
      this.addType = addType
      this.fieldIndex = -1
      this.fieldDetail = {}
      this.showAddField = true
    },

    // 编辑字段
    editField(row, index, addType) {
      this.addType = addType
      this.fieldIndex = index
      this.fieldDetail = row
      this.showAddField = true
    },

    // 删除字段
    deleteField(row, index, addType) {
      if (addType === 'person') {
        this.form.personTypeFields.splice(index, 1)
      } else if (addType === 'company') {
        this.form.companyTypeFields.splice(index, 1)
      }
    },

    // 获取详情
    getDetail() {
      const data = {
        id: this.id
      }
      getActivityDetail(data).then(res => {
        const {
          activeTypeId,
          coverImg,
          title,
          activityStartDate,
          activityEndDate,
          address,
          isEnroll,
          content
        } = res
        this.form = {
          activeTypeId,
          coverImg,
          title,
          activityDateRange: [activityStartDate, activityEndDate],
          address,
          isEnroll,
          content
        }
      }).catch(() => {})
    },

    // 取消
    close() {
      this.$emit('close')
    },

    // 确认
    confirm() {
      if (this.type === 'add') {
        this.addHandle()
      } else {
        this.editHandle()
      }
    },

    // 新增
    addHandle() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          const [activityEndDate = '', activityStartDate = ''] = this.form?.activityDateRange || []
          const data = {
            siteId: this.currentSite.id,
            ...this.form,
            activityEndDate,
            activityStartDate
          }
          console.log(data)
          createActivity(data).then(() => {
            this.$message.success('新增成功')
            this.loading = false
            this.$emit('confirm')
            this.close()
          }).catch(() => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    },

    // 编辑
    editHandle() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.loading = true
          // const data = {
          //   ...this.form,
          //   id: this.id,
          //   siteId: this.currentSite.id
          // }
          // editGasProduct(data).then(() => {
          //   this.$message.success('编辑成功')
          //   this.loading = false
          //   this.$emit('confirm')
          //   this.close()
          // }).catch(() => {
          //   this.loading = false
          // })
        } else {
          return false
        }
      })
    },

    // 关闭弹窗
    closeHandle() {
      this.showAddField = false
    },

    // 确认添加字段
    confirmHandle(data) {
      if (data.type === 'person') {
        if (data.index > -1) {
          this.$set(this.form.personTypeFields, data.index, data.form)
        } else {
          this.form.personTypeFields.push(data.form)
        }
      } else if (data.type === 'company') {
        if (data.index > -1) {
          this.$set(this.form.companyTypeFields, data.index, data.form)
        } else {
          this.form.companyTypeFields.push(data.form)
        }
      }
      this.closeHandle()
    },

    // 上传图片处理
    uploadHandle(payload, name, prop) {
      const fileList = payload.fileList
      const result = []
      fileList.map(item => {
        result.push(item.url)
      })
      this.form[name] = result.join(',')
      this.$refs.form.validateField(prop)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-select,.el-date-editor{
  width: 100%;
}
.add-field{
  margin: 10px 0;
}
.form-bottom-box{
  text-align: center;
}

</style>
